<template>
    <div v-if="!islogin">
        <span>请输入用户名</span>
        <el-input v-model.trim="username" style="width:210px"></el-input>

        <el-button @click="entryChat">进入聊天室</el-button>
    </div>

    <div v-else style="width:500px">
        <h1 style="border-bottom:1px solid">聊天室</h1>
        <!-- 消息内容 -->
        <div>
            <div class="item" v-for="item in msgList" :key="item">
                <div class="title">
                    <span>{{ item.username }}</span>
                    <span>{{ item.createTime }}</span>
                </div>
                <div class="content">{{ item.content }}</div>
            </div>
        </div>

        <el-input v-model="msg" type="textarea" style="width:100%"> </el-input>
        <el-button @click="handleSend">发送</el-button>
    </div>
</template>

<script setup>
import { onMounted, ref } from "vue"
import { Ws } from './ws.js'

const username = ref('')
const islogin = ref(false)
const ws = ref(null)

onMounted(() => {
    const name = localStorage.getItem('chat_username')
    if (name) {
        username.value = name
        islogin.value = true

        // websocket连接
        ws.value = new Ws()

        ws.value.on((e) => {
            console.log('收到消息', e);

            msgList.value.push(e)
        })

    } else {
        islogin.value = false
    }
})

const entryChat = () => {
    if (!username.value) {
        alert('请输入聊天用户名')
        return
    }
    localStorage.setItem('chat_username', username.value)
    islogin.value = true
}

const msgList = ref([])
// 发送消息
const msg = ref('')
const handleSend = () => {
    if (msg.value) {
        ws.value.send(JSON.stringify({
            username: username.value,
            createTime: new Date(),
            content: msg.value
        }))
    }
}
</script>

<style lang="scss" scoped>
.title {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
</style>